<template>
  <div class="view-flex" v-bind="$attrs">
    <px-scrollbar ref="scrollbarRef" class="inspect-task-detail-content" @scroll="handleScroll">
      <div ref="basicsRef">
        <div class="view-equip-title">基础信息</div>
        <ColumnsTable :columns="INSPECTTASKDETAIL_BASEINFO_COLUMNS" :data="formValue">
          <template #value="{ scope }">
            <template v-if="scope.prop === 'checkAreaDesc' && formValue.checkAreaDesc">
              <px-tag
                v-for="(item, index) in formValue.checkAreaDesc.split(',')"
                :key="index"
                class="ml-2"
                type="info"
                style="margin-top: 2px; margin-bottom: 2px"
                >{{ item }}</px-tag
              >
            </template>
            <template v-if="scope.prop === 'checkType' && formValue.checkType">
              {{ dealCheckTypeName(formValue.checkType) }}
            </template>
          </template>
        </ColumnsTable>
      </div>
      <px-form ref="ruleFormRef" :scroll-to-error="true" :inline="false" :model="formValue" label-position="right" label-width="80px">
        <div ref="contentRef" class="view-mb20">
          <div class="view-equip-title">巡检作业内容</div>
          <EditDropDown
            v-for="(eqpItem, eqpIndex) in formValue.checkJobContentList"
            ref="ruleChildrenRef"
            :key="eqpItem.eqpId"
            :dropdownTitle="`${eqpItem.eqpName}（${eqpItem.eqpId}）`"
          >
            <template v-slot:content>
              <SubEditDropDown
                v-for="(ruleItem, ruleIndex) in eqpItem.checkContentList"
                :key="`SubEditDropDown${ruleIndex}`"
                :dropdownTitle="`${ruleItem.checkTaskRuleContent}`"
              >
                <template v-slot:content>
                  <LazyRender>
                    <px-table :data="ruleItem.list" style="margin-bottom: 18px" class="equip-table inner-tabel" size="small" max-height="400" border>
                      <px-table-column
                        v-for="(item, colIndex) in tableColumns"
                        :key="`table${colIndex}`"
                        :label="item.label"
                        :prop="item.prop"
                        :min-width="item.minWidth"
                        :align="item.align"
                        :show-overflow-tooltip="item.showOverflowTooltip"
                        :fixed="item.fixed"
                      />
                      <px-table-column label="巡检结果" min-width="200" fixed="right">
                        <template #header>
                          <div>
                            <label class="must">巡检结果</label>
                          </div>
                        </template>
                        <template #default="scope">
                          <!-- {{ render(scope) }} -->
                          <template v-if="scope.row.checkContentRange">
                            <TaskFormAction
                              v-model:itemValue="formValue.checkJobContentList[eqpIndex].checkContentList[ruleIndex].list[scope.$index].result"
                              :disabled="disabled"
                              :validated="validated"
                              :itemProps="['checkJobContentList', eqpIndex, 'checkContentList', ruleIndex, 'list', scope.$index, 'result']"
                              :formValue="formValue"
                              :defaultvalue="scope.row.result"
                              :statusRange="scope.row.checkContentRangeValue"
                              :status="scope.row.checkContentRange"
                            />
                          </template>
                        </template>
                      </px-table-column>
                    </px-table>
                  </LazyRender>
                </template>
              </SubEditDropDown>
              <px-checkbox v-show="!disabled && eqpItem.checkType === 'equipment'" v-model="eqpItem.checked" label="发起维修工单" size="large" />
              <Maintain
                v-if="!disabled && eqpItem.checked"
                v-model="eqpItem.maintenanceWorkOrderList"
                :moduleName="moduleName"
                :approvalList="approvalList"
                :itemProps="['checkJobContentList', eqpIndex, 'maintenanceWorkOrderList']"
                :shareData="{ faultLevelList }"
                :visible="eqpItem.checked"
              />
            </template>
          </EditDropDown>
        </div>
        <div v-if="data.taskStatus !== 1 && !disabled" ref="resultRef">
          <div class="view-equip-title">巡检总结</div>
          <px-form-item label="现场照片" prop="fileList">
            <PhotoUpload photoType="add" :photoList="formValue.fileList" :photoData="{ moduleName: moduleName }" @changePhotoList="changePhotoList" />
          </px-form-item>
          <px-form-item label="总结说明" prop="summary">
            <px-input
              v-model="formValue.summary"
              type="textarea"
              placeholder="请输入总结说明"
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="1000"
              clearable
            />
          </px-form-item>
        </div>
      </px-form>
    </px-scrollbar>
    <WidgetRouter :router-list="routerList" :scrollbar-ref="scrollbarRef" :scroll-top="scrollTop" />
  </div>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { getModuleName } from "@/api/erc/maintain";
import LazyRender from "@/components/LazyRender/index.vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { onMounted, reactive, ref, toRef, toRefs, watch, watchEffect } from "vue";
import ColumnsTable from "../../components/ColumnsTable.vue";
import SubEditDropDown from "../../components/SubEditDropDown.vue";
import { WidgetRouter } from "../../components/index";
import { INSPECTTASKDETAIL_BASEINFO_COLUMNS } from "../config";
import Maintain from "./Maintain.vue";
import TaskFormAction from "./TaskFormAction.vue";

import { debounce } from "@pureadmin/utils";
// import { taskForm } from "../../types";
import type { FormInstance } from "px-ui";
const props = defineProps(["data", "disabled", "moduleName"]);
// const formValue = ref<taskForm>(props?.data);
const formValue: any = defineModel();
const validated = ref(false);
const approvalList = ref([]);
const moduleName = ref("");
const checkTypeArr = { equipment: "设备巡检", environment: "环境巡检" };
const dealCheckTypeName = checkType => {
  if (!checkType || !checkType.length) return "";
  return checkType.reduce((acc, cur) => {
    if (!acc) return checkTypeArr[cur];
    return acc + "," + checkTypeArr[cur];
  }, "");
};
// 获取getModuleName
const getModuleNameValue = async () => {
  const data: any = await getModuleName();
  moduleName.value = data;
};
const handleGetApprovalList = async () => {
  approvalList.value = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
};
onMounted(async () => {
  if (props.data) {
    formValue.value = { ...props.data };

    faultLevelList.value = await queryDictData({ typeCode: "ERC_MAINTENANCE_WEIGHT" });
  }
  getModuleNameValue();
  handleGetApprovalList();
});
watch(
  () => props.data,
  () => {
    formValue.value = { ...props.data };
  }
);
const ruleFormRef = ref<InstanceType<typeof FormInstance>>();
defineExpose({
  form: ruleFormRef,
  formValue,
  validated
});
const state = reactive<any>({
  faultLevelList: [],
  tableColumns: [
    { prop: "checkItem", label: "巡检项", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
    { prop: "checkContent", label: "巡检内容", minWidth: "160", showOverflowTooltip: true }
  ]
});
const { tableColumns, faultLevelList } = toRefs(state);
const changePhotoList = (list: any[]) => {
  const photoIds = list.map(item => item.id || item.response?.data?.id);
  formValue.value.photoIds = photoIds.join(",");
};
// 执行结果变化
// const handleTaskFormActionChange = (value: any, eqpIndex: number, ruleIndex: number, scopeIndex: number, scopeValue) => {
//   formValue.value.checkJobContentList[eqpIndex].checkContentList[ruleIndex].list[scopeIndex].result = value;
// };

//右侧滚动导航
const scrollbarRef = ref(null);
const routerList = ref([]);
const scrollTop = ref();
//折叠面板ref
const basicsRef = ref(null);
const contentRef = ref(null);
const ruleChildrenRef = ref(null);
const resultRef = ref(null);
//右侧滚动导航相关函数
const handleScroll = debounce(({ scrollTop: curScrollTop }) => {
  scrollTop.value = curScrollTop;
}, 200);
const scrollInit = () => {
  let routerName = "基本信息,巡检作业内容";
  let routerRefs = [basicsRef, contentRef];
  if (props.data.taskStatus !== 1 && !props.disabled) {
    // 状态为未开始不显示巡检总结
    routerName = "基本信息,巡检作业内容,巡检总结";
    routerRefs = [basicsRef, contentRef, resultRef];
  }
  let children = null;

  if (props.data && ruleChildrenRef.value) {
    children = props.data.checkJobContentList.map((item, index) => {
      return { ref: toRef(ruleChildrenRef.value[index]?.$el), name: item.eqpName };
    });
  }

  routerList.value = routerName.split(",").map((item, index) => {
    if (item === "巡检作业内容") {
      return { ref: routerRefs[index], name: item, children };
    } else {
      return { ref: routerRefs[index], name: item };
    }
  });
};
watchEffect(() => {
  scrollInit();
});
// onBeforeMount(() => {
//   getModuleNameValue();
// });
</script>

<style lang="scss" scoped>
.view-flex {
  position: relative;
  display: flex;
  height: calc(100vh - 260px);
  overflow: hidden;

  .view-equip-title {
    height: 22px;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
    line-height: 22px;
    color: rgb(0 0 0 / 80%);
  }

  :deep(.inner-tabel) {
    width: 100%;

    .px-table__header thead tr th {
      font-size: 14px;
      font-weight: bold;
      color: #000;
      background-color: #e7eefb !important;
    }

    td.px-table__cell div {
      width: 100%;
    }
  }

  :deep(.inspect-task-detail-content) {
    width: 100%;
    min-width: 500px;
  }

  :deep(.px-table__header) {
    .must::before {
      margin-right: 4px;
      color: var(--px-color-danger);
      content: "*";
    }
  }
}

.view-task-detail {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;

  .view-task-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text {
      margin-left: 20px;
      font-size: 20px;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
    }

    .status {
      display: flex;
      flex-direction: row;
      align-items: center;

      .circle {
        width: 8px;
        height: 8px;
        margin-right: 5px;
        margin-left: 8px;
        border-radius: 50%;
      }
    }
  }
}

.view-mb20 {
  margin-bottom: 20px;
}
</style>
